/*********************************************************
          File Name:skip_hole.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Mon 26 Oct 2015 08:21:55 PM CST
**********************************************************/

#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>

// -D_GUN_SOURCE=1

int main(int argc, char *argv[])
{
        if(argc != 3)
        {
                fprintf(stderr, "%s src dst\n", argv[0]);
                exit(1);
        }

        int ifd, ofd;
        off_t len, size = 0;
        struct stat tmp;
        void *buf = NULL;

        stat(argv[1], &tmp);
        len = tmp.st_size;

        ifd = open(argv[1], O_RDONLY);
        ofd = open(argv[2], O_CREAT|O_RDWR, 0644);

        if(ifd == -1 || ofd == -1)
        {
                fprintf(stderr, "Error: %s\n", strerror(errno));
                exit(1);
        }

        off_t res1 = 0, res2 = 0;
        
        while(res1 < len && res2 < len)
        {
                res1 = lseek(ifd, res2, SEEK_DATA);
                res2 = lseek(ifd, res1, SEEK_HOLE);

                size = res1 > res2 ? res1 - res2 : res2 - res1;
                buf = malloc(size);
                read(ifd, buf, size);
                
                lseek(ofd, res1, SEEK_SET);
                write(ofd, buf, size);
                free(buf);
                buf = NULL;
                printf("res1 = %lu\tres2 = %lu\n", res1, res2);
        }

        close(ifd);
        close(ofd);

        return 0;
}
